package site.icesky.springboot.rocketmq.service;

import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.common.protocol.heartbeat.MessageModel;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import site.icesky.springboot.rocketmq.mqconsumer.AbstractRocketMqConsumer;
import site.icesky.springboot.rocketmq.service.WorkerMessageManager;
import site.icesky.springboot.rocketmq.util.SpringContextUtil;

import java.util.List;

/**
 * @ClassName: WorkerConsumer <br>
 * @Description: 实际消费处理 <br>
 * @Package: site.icesky.springboot.rocketmq.mq <br>
 * @author: suitianmou <br>
 * @Date: 2020/5/23-20:12 <br>
 * @version: 1.0 <br>
 * @see <br>
 * @since (从产品的哪一个版本此类被添加进来 ( 可选))<br>
 * 修改历史: <br>
 * 修改时间             修改人           版本变更           修改说明<br>
 * -----------------------------------------------------<br>
 * <br>
 */
@Service
public class MqConsumerService extends AbstractRocketMqConsumer {

    @Value("$(rocketmq.consumer.group)")
    private String consumerGroup;

    @Value("${rocketmq.consumer.topic}")
    private String consumerTopic;

    private WorkerMessageManager getService() {
        return SpringContextUtil.getBean(WorkerMessageManager.class);
    }

    @Override
    public void init() {
        // 初始化mq
        super.necessary(consumerTopic, "*", "", MessageModel.CLUSTERING, consumerGroup);

        // 监听器
        registerMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage
                    (List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {

                System.out.printf("%s消费到[%d]条消息:[%s]详情:%s\n", Thread.currentThread().getName(),
                        list.size(), consumeConcurrentlyContext, list);
                for( MessageExt msg : list){
                    String message = new String( msg.getBody());
                    System.out.println("消息内容是:[%s]" + message);
                }
                // 接收消息
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });
    }
}
